home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 3006 / 3006.xpi / components / dhDownloadMgr.js < prev    next >
Text File  |  2010-01-15  |  16KB  |  481 lines

  1. /******************************************************************************
  2.  *            Copyright (c) 2006-2009 Michel Gutierrez. All Rights Reserved.
  3.  ******************************************************************************/
  4.  
  5. /**
  6.  * Constants.
  7.  */
  8.  
  9. const NS_DLMGR_CID = Components.ID("{dc9206a8-fe97-4214-b9a7-e07e584c6710}");
  10. const NS_DLMGR_PROG_ID = "@downloadhelper.net/download-manager;1";
  11. const DHNS = "http://downloadhelper.net/1.0#";
  12.  
  13. var Util=null;
  14.  
  15. /**
  16. * Object constructor
  17. */
  18. function DLMgr() {
  19.     try {
  20.         //dump("[DLMgr] constructor\n");
  21.         this.qDatasource=Components.classes['@mozilla.org/rdf/datasource;1?name=in-memory-datasource'].
  22.               createInstance(Components.interfaces.nsIRDFDataSource);
  23.         var prefService=Components.classes["@mozilla.org/preferences-service;1"]
  24.             .getService(Components.interfaces.nsIPrefService);
  25.         this.pref=prefService.getBranch("dwhelper.");
  26.         this.counters=[];
  27.         this.currents=[];
  28.         this.queuedEntries={};
  29.     } catch(e) {
  30.         dump("[DLMgr] !!! constructor: "+e+"\n");
  31.     }
  32. }
  33.  
  34. DLMgr.prototype = {
  35.     get queueDatasource() { return this.qDatasource; },
  36.     get downloadMode() { 
  37.         var mode="onebyone";
  38.         try { mode=this.pref.getCharPref("download-mode"); } catch(e) {}
  39.         return mode;
  40.     }
  41. }
  42.  
  43. DLMgr.prototype.download=function(listener,entry,ctx) {
  44.     //dump("[DLMgr] download()\n");
  45.     switch(this.downloadMode) {
  46.         case "normal":
  47.             this.doDownload(listener,entry,ctx);
  48.             break;
  49.         case "onebyone":
  50.         case "controlled":
  51.             this.queueDownload(listener,entry,ctx);
  52.             break;
  53.     }
  54. }
  55.  
  56. DLMgr.prototype.doDownload=function(listener,entry,ctx) {
  57.     
  58.     try {
  59.     
  60.     //dump("[DLMgr] doDownload()\n");
  61.     var file=null;
  62.     if(entry.has("dl-file")) {
  63.         file=entry.get("dl-file",Components.interfaces.nsIFile);
  64.     } else {
  65.          file=Components.classes["@mozilla.org/file/directory_service;1"]
  66.                                  .getService(Components.interfaces.nsIProperties)
  67.                                  .get("TmpD", Components.interfaces.nsIFile);
  68.          if(entry.has("file-name"))
  69.              file.append(Util.getPropsString(entry,"file-name"));
  70.          else
  71.              file.append("dwhelper-dl");
  72.          file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644);
  73.          entry.set("dl-file",file);
  74.     }
  75.     
  76.     var url = Components.classes["@mozilla.org/network/standard-url;1"].createInstance(Components.interfaces.nsIURI);
  77.     url.spec = Util.getPropsString(entry,"media-url");
  78.     var fileURL = makeFileURI(file);
  79.     var persist = makeWebBrowserPersist();
  80.     
  81.     const nsIWBP = Components.interfaces.nsIWebBrowserPersist;    
  82.     persist.persistFlags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
  83.     persist.persistFlags |= nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
  84.     
  85.     var tr = Components.classes["@mozilla.org/transfer;1"].createInstance(Components.interfaces.nsITransfer);
  86.  
  87.     var progress=new Progress(tr,this,listener,entry,ctx);
  88.  
  89.     persist.progressListener = progress;
  90.     
  91.     var referrer=Util.getPropsString(entry,"referrer");
  92.     if(referrer!=null) {
  93.         var refStr=referrer;    
  94.         referrer = Components.classes["@mozilla.org/network/standard-url;1"].createInstance(Components.interfaces.nsIURI);
  95.         referrer.spec = refStr;
  96.     }
  97.  
  98.     persist.saveURI(url,null, referrer, null, null,fileURL);
  99.     tr.init(url,fileURL, "", null, null, null, persist);
  100.  
  101.     } catch(e) {
  102.         dump("!!! [DLMgr] doDownload(): "+e+"\n");
  103.     }
  104. }
  105.  
  106. DLMgr.prototype.queueDownload=function(listener,entry,ctx) {
  107.     //dump("[DLMgr] queueDownload()\n");
  108.     try {
  109.         var dEntry=Util.createAnonymousNodeS(this.qDatasource,"urn:root");
  110.         Util.setPropsString(entry,"download-node-value",dEntry.Value);
  111.         //dump("[DLMgr] queued "+dEntry.Value+"\n");
  112.         var label;
  113.         if(entry.has("cv-file")) {
  114.             label=entry.get("cv-file",Components.interfaces.nsILocalFile).leafName;
  115.         } else if(entry.has("dl-file")) {
  116.             label=entry.get("dl-file",Components.interfaces.nsILocalFile).leafName;
  117.         } else {
  118.             label=Util.getPropsString(entry,"label")
  119.         }
  120.         Util.setPropertyValueRS(this.qDatasource,dEntry,DHNS+"label",label);
  121.         Util.setPropertyValueRS(this.qDatasource,dEntry,DHNS+"status","queued");
  122.         this.queuedEntries[dEntry.Value]={
  123.                 listener: listener,
  124.                 entry: entry,
  125.                 ctx: ctx
  126.         }
  127.         this.checkTransfer();    
  128.     } catch(e) {
  129.         dump("!!! [DLMgr] queueDownload(): "+e+"\n");
  130.     }
  131. }
  132.  
  133. DLMgr.prototype.checkTransfer=function() {
  134.     //dump("[DLMgr] checkTransfer()\n");
  135.     var maxDL=1;
  136.     if(this.downloadMode=="controlled") {
  137.         maxDL=this.pref.getIntPref("download.controlled.max");
  138.         if(maxDL<1) {
  139.             maxDL=1;
  140.             this.pref.setIntPref("download.controlled.max",maxDL);
  141.         }
  142.     }
  143.     var entries=Util.getChildResourcesS(this.qDatasource,"urn:root",{});
  144.     while(this.currents.length<maxDL && entries.length>0) {
  145.         var dEntry=null;
  146.         for(var i in entries) {
  147.             var status=Util.getPropertyValueRS(this.qDatasource,entries[i],DHNS+"status");
  148.             if(status=="queued") {
  149.                 dEntry=entries[i];
  150.                 break;
  151.             }
  152.         }
  153.         if(dEntry==null)
  154.             break;
  155.         var data=this.queuedEntries[dEntry.Value];
  156.         Util.setPropertyValueRS(this.qDatasource,dEntry,DHNS+"status","downloading");
  157.         //dump("[DLMgr] starting "+dEntry.Value+"\n");
  158.         this.doDownload(data.listener,data.entry,data.ctx);
  159.         this.currents.push(dEntry.Value);
  160.     }
  161.     var count=entries.length;
  162.     for(var i in this.counters) {
  163.         if(count==0)
  164.             this.counters[i].setAttribute("value","");
  165.         else
  166.             this.counters[i].setAttribute("value","("+count+")");
  167.     }
  168. }
  169.  
  170. DLMgr.prototype.transferDone = function(status,request,listener,entry,ctx) {
  171.     //dump("[DLMgr] transferDone()\n");
  172.  
  173.     var code=0;
  174.     try {
  175.         var hc=request.QueryInterface(Components.interfaces.nsIHttpChannel);
  176.         code=hc.responseStatus;
  177.     } catch(e) {}
  178.  
  179.     try {
  180.  
  181.         if(status==0 && code==200) {
  182.             this.incrementDownloadCount();
  183.         }
  184.         
  185.         var nodeValue=Util.getPropsString(entry,"download-node-value");
  186.         
  187.         //dump("[DLMgr] done "+nodeValue+"\n");
  188.         delete this.queuedEntries[nodeValue];
  189.     
  190.         Util.removeChildSS(this.qDatasource,"urn:root",nodeValue);
  191.         Util.removeReferenceS(this.qDatasource,nodeValue);            
  192.  
  193.         for(var i in this.currents) {
  194.             if(this.currents[i]==nodeValue) {
  195.                 //dump("[DLMgr] purged "+nodeValue+"\n");
  196.                 this.currents.splice(i,1);
  197.                 break;
  198.             }
  199.         }
  200.  
  201.         this.checkTransfer();
  202.     
  203.     } catch(e) {
  204.         dump("!!! [DLMgr] transferDone(): "+e+"\n");
  205.     }
  206.  
  207.     try {
  208.         if(listener)
  209.             listener.downloadFinished(status,request,entry,ctx);
  210.     } catch(e) {
  211.         dump("!!! [DLMgr] transferDone()/downloadFinished(): "+e+"\n");
  212.     }
  213. }
  214.  
  215. DLMgr.prototype.incrementDownloadCount = function() {
  216.     var dwcount=0;
  217.     try {
  218.         dwcount=this.pref.getIntPref("download-count");
  219.     } catch(e) {
  220.     }
  221.     dwcount++;
  222.     this.pref.setIntPref("download-count",dwcount);
  223.     if(dwcount%100==0) {
  224.         this.donate(dwcount);
  225.     }
  226.     if(this.pref.getBoolPref("disable-dwcount-cookie")==false) {
  227.         try {
  228.             var cMgr = Components.classes["@mozilla.org/cookiemanager;1"].
  229.                getService(Components.interfaces.nsICookieManager2);
  230.             try {
  231.                 cMgr.add(".downloadhelper.net","/","dwcount",""+dwcount,false,true,new Date().getTime()/1000+10000000);
  232.                 cMgr.add(".vidohe.com","/","dwcount",""+dwcount,false,true,new Date().getTime()/1000+10000000);
  233.             } catch(e) {
  234.                 cMgr.add(".downloadhelper.net","/","dwcount",""+dwcount,false,true,false,new Date().getTime()/1000+10000000);
  235.                 cMgr.add(".vidohe.com","/","dwcount",""+dwcount,false,true,false,new Date().getTime()/1000+10000000);
  236.             }
  237.         } catch(e) {
  238.             dump("!!! [DhDownloadMgr] incrementDownloadCount() "+e+"\n");
  239.         }
  240.     }
  241. }
  242.  
  243. DLMgr.prototype.donate=function(count) {
  244.     if(this.pref.getBoolPref("donate-not-again"))
  245.         return;
  246.     try {
  247.         var cvMgr=Components.classes["@downloadhelper.net/convert-manager-component"]
  248.                                           .getService(Components.interfaces.dhIConvertMgr);
  249.         var cvInfo=cvMgr.getInfo();
  250.         if(cvInfo.get("windows",Components.interfaces.nsISupportsPRBool).data==true &&
  251.                 cvInfo.get("unregistered",Components.interfaces.nsISupportsPRBool).data==false)
  252.             return; // don't request donation to those who have a license
  253.     } catch(e) {}
  254.     var options="chrome,centerscreen";
  255.     try {
  256.         var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  257.                   .getService(Components.interfaces.nsIWindowMediator);
  258.         var w = wm.getMostRecentWindow("navigator:browser");
  259.         w.open('chrome://dwhelper/content/donate.xul','dwhelper-dialog',options);
  260.     } catch(e) {
  261.         dump("!!! [DhDownloadMgr] donate() "+e+"\n");
  262.     }
  263. }
  264.  
  265. DLMgr.prototype.getDefaultDir=function() {
  266.     var file=null;
  267.     try {
  268.         file = Components.classes["@mozilla.org/file/directory_service;1"]
  269.                          .getService(Components.interfaces.nsIProperties)
  270.                          .get("Home", Components.interfaces.nsIFile);
  271.     } catch(e) {
  272.         try {
  273.             file=Components.classes["@mozilla.org/file/directory_service;1"]
  274.                 .getService(Components.interfaces.nsIProperties)
  275.                 .get("TmpD", Components.interfaces.nsIFile);
  276.         } catch(e) {
  277.         }
  278.     }
  279.     if(!file.exists()) {
  280.         throw(DWHUtil.getText("error.nohome"));
  281.     }
  282.     file.append("dwhelper");
  283.     return file;
  284. }
  285.  
  286. DLMgr.prototype.getDownloadDirectory=function() {
  287.  
  288.     var fileName=Util.getUnicharPref(this.pref,"storagedirectory",null);
  289.     
  290.     var file;
  291.     if(fileName==null || fileName.length==0) {
  292.         file=this.getDefaultDir();
  293.     } else {
  294.         try {
  295.             file=Components.classes["@mozilla.org/file/local;1"].
  296.                 createInstance(Components.interfaces.nsILocalFile);
  297.             file.initWithPath(fileName);
  298.             if(file.exists()==false || file.isWritable()==false || file.isDirectory()==false)
  299.                 file=this.getDefaultDir();
  300.         } catch(e) {
  301.             file=this.getDefaultDir();
  302.         }
  303.     }
  304.     if(!file.exists()) {
  305.         file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755);
  306.     }
  307.     Util.setUnicharPref(this.pref,"storagedirectory",file.path);
  308.     return file;
  309. }
  310.  
  311. DLMgr.prototype.setDownloadDirectory=function(fileDir) {
  312.     if(!fileDir.isDirectory())
  313.         fileDir=fileDir.parent;
  314.     Util.setUnicharPref(this.pref,"storagedirectory",fileDir.path);
  315. }
  316.  
  317. DLMgr.prototype.removeFromQueue=function(entries,length) {
  318.     for(var i in entries) {
  319.         var entry=entries[i];
  320.         var status=Util.getPropertyValueRS(this.qDatasource,entry,DHNS+"status");
  321.         if(status=="queued") {
  322.             delete this.queuedEntries[entry.Value]
  323.             Util.removeChildSR(this.qDatasource,"urn:root",entry);
  324.             Util.removeReference(this.qDatasource,entry);            
  325.         }
  326.     }
  327. }
  328.  
  329. DLMgr.prototype.registerCounter = function(counter) {
  330.     //dump("[DLMgr] registerCounter()\n");
  331.     this.counters.push(counter);
  332. }
  333.  
  334. DLMgr.prototype.unregisterCounter = function(counter) {
  335.     //dump("[DLMgr] unregisterCounter()\n");
  336.     this.counters.splice(this.counters.indexOf(counter),1);
  337. }
  338.  
  339. DLMgr.prototype.QueryInterface = function(iid) {
  340.     //dump("[DLMgr] QueryInterface("+iid+")\n");
  341.     if(
  342.         iid.equals(Components.interfaces.dhIDownloadMgr) ||
  343.         iid.equals(Components.interfaces.nsISupports)
  344.     ) {
  345.         return this;
  346.     }
  347.     throw Components.results.NS_ERROR_NO_INTERFACE;
  348. }
  349.  
  350. var vDLMgrModule = {
  351.     firstTime: true,
  352.     
  353.     /*
  354.      * RegisterSelf is called at registration time (component installation
  355.      * or the only-until-release startup autoregistration) and is responsible
  356.      * for notifying the component manager of all components implemented in
  357.      * this module.  The fileSpec, location and type parameters are mostly
  358.      * opaque, and should be passed on to the registerComponent call
  359.      * unmolested.
  360.      */
  361.     registerSelf: function (compMgr, fileSpec, location, type) {
  362.  
  363.         if (this.firstTime) {
  364.             this.firstTime = false;
  365.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  366.         }
  367.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  368.         compMgr.registerFactoryLocation(NS_DLMGR_CID,
  369.                                         "DLMgr",
  370.                                         NS_DLMGR_PROG_ID, 
  371.                                         fileSpec,
  372.                                         location,
  373.                                         type);
  374.     },
  375.  
  376.     unregisterSelf: function(compMgr, fileSpec, location) {
  377.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  378.         compMgr.unregisterFactoryLocation(NS_DH_DLMGR_CID, fileSpec);
  379.     },
  380.  
  381.     /*
  382.      * The GetClassObject method is responsible for producing Factory and
  383.      * SingletonFactory objects (the latter are specialized for services).
  384.      */
  385.     getClassObject: function (compMgr, cid, iid) {
  386.         if (!cid.equals(NS_DLMGR_CID)) {
  387.             throw Components.results.NS_ERROR_NO_INTERFACE;
  388.         }
  389.  
  390.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  391.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  392.         }
  393.  
  394.         return this.vDLMgrFactory;
  395.     },
  396.  
  397.     /* factory object */
  398.     vDLMgrFactory: {
  399.         /*
  400.          * Construct an instance of the interface specified by iid, possibly
  401.          * aggregating it with the provided outer.  (If you don't know what
  402.          * aggregation is all about, you don't need to.  It reduces even the
  403.          * mightiest of XPCOM warriors to snivelling cowards.)
  404.          */
  405.         createInstance: function (outer, iid) {
  406.             if (outer != null) {
  407.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  408.             }
  409.     
  410.             if(Util==null) {
  411.                 Util=Components.classes["@downloadhelper.net/util-service;1"]
  412.                     .getService(Components.interfaces.dhIUtilService);
  413.                 try {
  414.                     var jsLoader=Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
  415.                         .getService(Components.interfaces.mozIJSSubScriptLoader);
  416.                     jsLoader.loadSubScript("chrome://global/content/contentAreaUtils.js");
  417.                 } catch(e) {
  418.                     dump("!!! [dhDownloadMgr] createInstance: "+e+"\n");
  419.                 }
  420.             }
  421.  
  422.             return new DLMgr().QueryInterface(iid);
  423.         }
  424.     },
  425.  
  426.     /*
  427.      * The canUnload method signals that the component is about to be unloaded.
  428.      * C++ components can return false to indicate that they don't wish to be
  429.      * unloaded, but the return value from JS components' canUnload is ignored:
  430.      * mark-and-sweep will keep everything around until it's no longer in use,
  431.      * making unconditional ``unload'' safe.
  432.      *
  433.      * You still need to provide a (likely useless) canUnload method, though:
  434.      * it's part of the nsIModule interface contract, and the JS loader _will_
  435.      * call it.
  436.      */
  437.     canUnload: function(compMgr) {
  438.         return true;
  439.     }
  440. };
  441.  
  442. function NSGetModule(compMgr, fileSpec) {
  443.     return vDLMgrModule;
  444. }
  445.  
  446. /*---------------------------------------------------------------------------------------*/
  447.  
  448. function Progress(tr,observer,listener,entry,ctx) {
  449.     this.tr=tr;
  450.     this.observer=observer;
  451.     this.listener=listener;
  452.     this.entry=entry;
  453.     this.ctx=ctx;
  454. }
  455.  
  456. Progress.prototype.onLocationChange=function(webProgress, request, location ) {
  457.     this.tr.onLocationChange(webProgress, request, location);
  458. }
  459.  
  460. Progress.prototype.onProgressChange=function(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress ) {
  461.     try {
  462.         this.tr.onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress );
  463.     } catch(e) {}
  464. }
  465.  
  466. Progress.prototype.onSecurityChange=function(webProgress, request, state ) {
  467.     this.tr.onSecurityChange(webProgress, request, state );
  468. }
  469.  
  470. Progress.prototype.onStateChange=function(webProgress, request, stateFlags, status ) {
  471.     this.tr.onStateChange(webProgress, request, stateFlags, status );
  472.     if(stateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP) {
  473.         this.observer.transferDone(status,request,this.listener,this.entry,this.ctx);
  474.     }
  475. }
  476.  
  477. Progress.prototype.onStatusChange=function(webProgress, request, status, message ) {
  478.     this.tr.onStatusChange(webProgress, request, status, message );
  479. }
  480.  
  481.